from flask_sqlalchemy import SQLAlchemy

# 初始化
db = SQLAlchemy()

# User 信息统计
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    ip_address = db.Column(db.String(45), nullable=True)  
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

# 文献列表
class Literature(db.Model):
    __tablename__ = 'literature'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), nullable=False)  # 文献标题
    authors = db.Column(db.String(500))  # 作者
    abstract = db.Column(db.Text)  # 摘要
    keywords = db.Column(db.String(500))  # 关键词
    publication = db.Column(db.String(200))  # 发表期刊/会议
    pub_year = db.Column(db.Integer)  # 发表年份
    doi = db.Column(db.String(100), unique=True)  # DOI号
    url = db.Column(db.String(500))  # 文献链接
    citation_count = db.Column(db.Integer, default=0)  # 被引用次数
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())  # 记录创建时间
    
    def __repr__(self):
        return f'<Literature {self.title}>'



# 检索记录
class SearchHistory(db.Model):
    __tablename__ = 'search_history'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))  # 关联用户ID
    search_term = db.Column(db.String(500), nullable=False)  # 检索词
    search_results = db.Column(db.Text)  # 检索结果
    search_time = db.Column(db.DateTime, default=db.func.current_timestamp())  # 检索时间
    
    def __repr__(self):
        return f'<SearchHistory {self.search_term}>'


# 用户检索次数剩余次数统计，按天给次数对于单个ip一天以10次为限，自动刷新
class SearchLimit(db.Model):
    __tablename__ = 'search_limits'
    id = db.Column(db.Integer, primary_key=True)
    ip_address = db.Column(db.String(50), nullable=False)  # IP地址
    search_count = db.Column(db.Integer, default=0)  # 当天已检索次数
    last_reset = db.Column(db.Date, default=db.func.current_date())  # 上次重置日期
    
    def __repr__(self):
        return f'<SearchLimit {self.ip_address}>'
    
    def can_search(self):
        """检查是否还能继续检索"""
        today = db.func.current_date()
        if self.last_reset < today:
            self.search_count = 0
            self.last_reset = today
            return True
        return self.search_count < 10  
    
    def increment_count(self):
        """增加检索次数"""
        if self.can_search():
            self.search_count += 1
            return True
        return False


# 访问量
class VisitCount(db.Model):
    __tablename__ = 'visit_count'
    id = db.Column(db.Integer, primary_key=True)
    count = db.Column(db.Integer, default=0)  # 访问次数


# 初始化数据库函数
def init_db(app):
    db.init_app(app)
    with app.app_context():
        db.create_all()